package myServer.handler;

import component.timeConsumingTask.CallbackTask;
import component.timeConsumingTask.CallbackTaskCollector;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import myServer.processor.LoginProcessor;
import myServer.session.ServerSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import protobuf.protoClass.ProtoMsg;

@ChannelHandler.Sharable
@Service("LoginRequestHandler")
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    LoginProcessor loginProcessor;
    @Autowired
    private ChatTransmitHandler chatTransmitHandler;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("收到一个新的连接，但是没有登录： " + ctx.channel().id());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (!(msg instanceof ProtoMsg.Message protoMessage)) {
            super.channelRead(ctx, msg);
            return;
        }
        //判断消息类型
        ProtoMsg.HeadType type = protoMessage.getType();
        if (!type.equals(loginProcessor.type())) {
            super.channelRead(ctx, msg);
            return;
        }

        ServerSession serverSession = new ServerSession(ctx.channel());
        //异步任务，处理登录的逻辑
        CallbackTaskCollector.add(new CallbackTask<Boolean>() {
            @Override
            public Boolean execute() {
                return loginProcessor.perform(serverSession, protoMessage);
            }

            //异步 登录成功
            @Override
            public void onBack(Boolean executeSucceed) {
                //每一个连接都需要对应一个心跳检测，所以心跳检测是多例的
                if (executeSucceed) {
                    ctx.pipeline()
                            .addAfter("login", "chat", chatTransmitHandler)
                            .addAfter("login", "heartBeat", new HeartBeatServerHandler())
                            .remove("login");
                    System.out.println("登录成功:" + serverSession.getUserAttribute());
                } else {
                    ServerSession.closeChannelBySession(ctx);
                    System.out.println("登录失败:" + serverSession.getUserAttribute());
                }
            }

            //异步 登陆失败
            @Override
            public void onException(Throwable t) {
                ServerSession.closeChannelBySession(ctx);
                System.out.println("登录失败:" + serverSession.getUserAttribute());
            }
        });

    }

}
